package edu.cmu.ibill.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import edu.cmu.ibill.util.StringProcessor;
import edu.cmu.ibill.util.validator;
import edu.cmu.ibill.databeans.PersonalBill;
import edu.cmu.ibill.databeans.User;
import edu.cmu.ibill.model.CategoryDictDAO;
import edu.cmu.ibill.model.Model;
import edu.cmu.ibill.model.UserDAO;
import edu.cmu.ibill.model.PersonalBillDAO;

/**
 * 
 * @author Yunkai Zhang
 * 15-637
 */


public class LoginAction extends Action {

	private UserDAO userDAO;
	private PersonalBillDAO personalbillDAO;
	private CategoryDictDAO catDAO;

	public LoginAction(Model model) {
		userDAO = model.getUserDAO();
		personalbillDAO = model.getPersonalBillDAO();
		catDAO=model.getCategoryDictDAO();
	}

	@Override
	public String getName() {
		return "login.do";
	}

	@Override
	public String perform(HttpServletRequest request) {

		List<String> errors = new ArrayList<String>();
		request.setAttribute("loginerrors", errors);

		if (request != null) {

			HttpSession session = request.getSession();

			String email = request.getParameter("email");
			String password = request.getParameter("password");
			
			boolean isPresent = ((email!=null) || (password!=null));
			
			email = StringProcessor.process(email);
			password = StringProcessor.process(password);
			
			request.setAttribute("email", email);

			
	        if (!isPresent) {
	        	errors.clear();
	            return "login.jsp";
	        }

			request.setAttribute("email", email);
			request.setAttribute("password", password);

			checkInput(errors, email, password);

			User user = null;

			if (errors.size() == 0)
				user = userDAO.Lookup(email);

			if (errors.size() == 0) {
				if (user == null)
					errors.add("invalid credentials");
				else if (!user.checkPassword(password)){
					errors.add("invalid credentials");}
				else {
					// login succeed
					session.setAttribute("user", user);
					PersonalBill[] pBills = personalbillDAO.LookupByUserId(user.getId());
					request.setAttribute("personalbills", pBills);
					request.setAttribute("categorydict", catDAO.getAllCategoryNames());
					return "manage.jsp";
				}
			}
		}
		request.setAttribute("logininprocess", "");
		return "login.jsp";

	}

	private void checkInput(List<String> errors, String email, String password) {
		if (email == null )
			errors.add("email is empty");
		else if(!validator.isValidEmail(email))
			errors.add("invalid format for email address");
		if (password == null || password.length() == 0)
			errors.add("password is empty");
	}

}
